#include <stdio.h>
#include <string.h>
#include "message.h"
#include "sir.h"#include <mysql/mysql.h>
#include <mysql/errmsg.h>
#include <time.h>

char pluginName[255] = "stationMeteo";
char subject[255]    = "";
char DBHost[255];
char DBName[255];
char DBUser[255];
char DBPassword[255];

MYSQL mysql;


int db_connect();

int init( char * _subject, sirElement * config ){
	if ( _subject != NULL )
	{
		strcpy ( subject, _subject );
	}	printf("Init plugin %s listenning %s \n", pluginName, subject);

	if ( config != NULL )
	{
		sirElement * search;
		char nomSection[ STRING_SIZE ];
		sprintf(nomSection, "%s:%s", pluginName, subject );
		if ( ! isSectionExists( config, nomSection ) )
		{
			strcpy(nomSection, pluginName );
		}
		
		search = getElement( config, nomSection, "DBHost" );
		strcpy ( DBHost, getElementValue( search, "") );

		search = getElement( config, nomSection, "DBName" );
		strcpy ( DBName, getElementValue( search, "") );

		search = getElement( config, nomSection, "DBUser" );
		strcpy ( DBUser, getElementValue( search, "") );

		search = getElement( config, nomSection, "DBPassword" );
		strcpy ( DBPassword, getElementValue( search, "") );

		if ( strcmp( "", DBHost) == 0
		    	|| strcmp( "", DBName) == 0
		    	|| strcmp( "", DBUser) == 0
		    	|| strcmp( "", DBPassword) == 0 )	
		{
			printf(" Incomplete Parameters for plugin %s in section %s\n", pluginName, nomSection);
			return 0;
		}
		if ( db_connect() == 0 )
		{
			return 0;
		}
	}
	return 1;}
int db_connect()
{
	mysql_init( &mysql );
	mysql_options( &mysql, MYSQL_READ_DEFAULT_GROUP, "option");
	if( mysql_real_connect(&mysql, DBHost, DBUser, DBPassword, DBName, 0, NULL, 0) )
	{
		printf("DB Connexion established Sucessfully\n");
	}
	else
	{
		printf("DB Connexion established Failed\n");
		return 0;
	}
	return 1;
}

char * parse ( Message * message ){
	char sql[1024];

	if ( message->message[0] == 'D' )
	{
		//message reçu : D267300001,296,64,24.94,26.00,25.75,27.50,24.94
		char * pchaine = strchr( message->message, ',');
		pchaine ++;
	
		sprintf(sql, "INSERT INTO mesures_sondes VALUES( date( now() ), time( now() ), %s)", pchaine);
	//	puts(sql);
		int res = mysql_query(&mysql, sql);
		if (  res != 0)
		{
			printf("%s : Error Insert into DB : %s\n", pluginName, mysql_error (&mysql));
			printf("CR = %d\n", res);
			printf("Connection attempt\n");
			db_connect();
		
		}	}
	else if ( message->message[0] == 'W' ) 
	{
		//char * pchaine = strchr( message->message, ',');

	}
	return message->message;
}
